/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.games.epkb.controller;

import it.polimi.games.epkb.controller.exceptions.IllegalOrphanException;
import it.polimi.games.epkb.controller.exceptions.NonexistentEntityException;
import it.polimi.games.epkb.controller.exceptions.PreexistingEntityException;
import it.polimi.games.epkb.entityClasses.CpuCore;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import it.polimi.games.epkb.entityClasses.Cpu;
import it.polimi.games.epkb.entityClasses.Component;
import it.polimi.games.epkb.entityClasses.CpuCorePower;
import java.util.ArrayList;
import java.util.Collection;
import javax.transaction.UserTransaction;

/**
 *
 * @author plebani
 */
public class CpuCoreJpaController implements Serializable {

    public CpuCoreJpaController(EntityManagerFactory emf) {
        this.utx = null;
        this.emf = emf;
    }

    public CpuCoreJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(CpuCore cpuCore) throws IllegalOrphanException, PreexistingEntityException, Exception {
        if (cpuCore.getCpuCorePowerCollection() == null) {
            cpuCore.setCpuCorePowerCollection(new ArrayList<CpuCorePower>());
        }
        List<String> illegalOrphanMessages = null;
        Component componentOrphanCheck = cpuCore.getComponent();
        if (componentOrphanCheck != null) {
            CpuCore oldCpuCoreOfComponent = componentOrphanCheck.getCpuCore();
            if (oldCpuCoreOfComponent != null) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("The Component " + componentOrphanCheck + " already has an item of type CpuCore whose component column cannot be null. Please make another selection for the component field.");
            }
        }
        if (illegalOrphanMessages != null) {
            throw new IllegalOrphanException(illegalOrphanMessages);
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Cpu idCPU = cpuCore.getIdCPU();
            if (idCPU != null) {
                idCPU = em.getReference(idCPU.getClass(), idCPU.getId());
                cpuCore.setIdCPU(idCPU);
            }
            Component component = cpuCore.getComponent();
            if (component != null) {
                component = em.getReference(component.getClass(), component.getId());
                cpuCore.setComponent(component);
            }
            Collection<CpuCorePower> attachedCpuCorePowerCollection = new ArrayList<CpuCorePower>();
            for (CpuCorePower cpuCorePowerCollectionCpuCorePowerToAttach : cpuCore.getCpuCorePowerCollection()) {
                cpuCorePowerCollectionCpuCorePowerToAttach = em.getReference(cpuCorePowerCollectionCpuCorePowerToAttach.getClass(), cpuCorePowerCollectionCpuCorePowerToAttach.getId());
                attachedCpuCorePowerCollection.add(cpuCorePowerCollectionCpuCorePowerToAttach);
            }
            cpuCore.setCpuCorePowerCollection(attachedCpuCorePowerCollection);
            em.persist(cpuCore);
            if (idCPU != null) {
                idCPU.getCpuCoreCollection().add(cpuCore);
                idCPU = em.merge(idCPU);
            }
            if (component != null) {
                component.setCpuCore(cpuCore);
                component = em.merge(component);
            }
            for (CpuCorePower cpuCorePowerCollectionCpuCorePower : cpuCore.getCpuCorePowerCollection()) {
                CpuCore oldIdCoreOfCpuCorePowerCollectionCpuCorePower = cpuCorePowerCollectionCpuCorePower.getIdCore();
                cpuCorePowerCollectionCpuCorePower.setIdCore(cpuCore);
                cpuCorePowerCollectionCpuCorePower = em.merge(cpuCorePowerCollectionCpuCorePower);
                if (oldIdCoreOfCpuCorePowerCollectionCpuCorePower != null) {
                    oldIdCoreOfCpuCorePowerCollectionCpuCorePower.getCpuCorePowerCollection().remove(cpuCorePowerCollectionCpuCorePower);
                    oldIdCoreOfCpuCorePowerCollectionCpuCorePower = em.merge(oldIdCoreOfCpuCorePowerCollectionCpuCorePower);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findCpuCore(cpuCore.getId()) != null) {
                throw new PreexistingEntityException("CpuCore " + cpuCore + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(CpuCore cpuCore) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            CpuCore persistentCpuCore = em.find(CpuCore.class, cpuCore.getId());
            Cpu idCPUOld = persistentCpuCore.getIdCPU();
            Cpu idCPUNew = cpuCore.getIdCPU();
            Component componentOld = persistentCpuCore.getComponent();
            Component componentNew = cpuCore.getComponent();
            Collection<CpuCorePower> cpuCorePowerCollectionOld = persistentCpuCore.getCpuCorePowerCollection();
            Collection<CpuCorePower> cpuCorePowerCollectionNew = cpuCore.getCpuCorePowerCollection();
            List<String> illegalOrphanMessages = null;
            if (componentNew != null && !componentNew.equals(componentOld)) {
                CpuCore oldCpuCoreOfComponent = componentNew.getCpuCore();
                if (oldCpuCoreOfComponent != null) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("The Component " + componentNew + " already has an item of type CpuCore whose component column cannot be null. Please make another selection for the component field.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (idCPUNew != null) {
                idCPUNew = em.getReference(idCPUNew.getClass(), idCPUNew.getId());
                cpuCore.setIdCPU(idCPUNew);
            }
            if (componentNew != null) {
                componentNew = em.getReference(componentNew.getClass(), componentNew.getId());
                cpuCore.setComponent(componentNew);
            }
            Collection<CpuCorePower> attachedCpuCorePowerCollectionNew = new ArrayList<CpuCorePower>();
            for (CpuCorePower cpuCorePowerCollectionNewCpuCorePowerToAttach : cpuCorePowerCollectionNew) {
                cpuCorePowerCollectionNewCpuCorePowerToAttach = em.getReference(cpuCorePowerCollectionNewCpuCorePowerToAttach.getClass(), cpuCorePowerCollectionNewCpuCorePowerToAttach.getId());
                attachedCpuCorePowerCollectionNew.add(cpuCorePowerCollectionNewCpuCorePowerToAttach);
            }
            cpuCorePowerCollectionNew = attachedCpuCorePowerCollectionNew;
            cpuCore.setCpuCorePowerCollection(cpuCorePowerCollectionNew);
            cpuCore = em.merge(cpuCore);
            if (idCPUOld != null && !idCPUOld.equals(idCPUNew)) {
                idCPUOld.getCpuCoreCollection().remove(cpuCore);
                idCPUOld = em.merge(idCPUOld);
            }
            if (idCPUNew != null && !idCPUNew.equals(idCPUOld)) {
                idCPUNew.getCpuCoreCollection().add(cpuCore);
                idCPUNew = em.merge(idCPUNew);
            }
            if (componentOld != null && !componentOld.equals(componentNew)) {
                componentOld.setCpuCore(null);
                componentOld = em.merge(componentOld);
            }
            if (componentNew != null && !componentNew.equals(componentOld)) {
                componentNew.setCpuCore(cpuCore);
                componentNew = em.merge(componentNew);
            }
            for (CpuCorePower cpuCorePowerCollectionOldCpuCorePower : cpuCorePowerCollectionOld) {
                if (!cpuCorePowerCollectionNew.contains(cpuCorePowerCollectionOldCpuCorePower)) {
                    cpuCorePowerCollectionOldCpuCorePower.setIdCore(null);
                    cpuCorePowerCollectionOldCpuCorePower = em.merge(cpuCorePowerCollectionOldCpuCorePower);
                }
            }
            for (CpuCorePower cpuCorePowerCollectionNewCpuCorePower : cpuCorePowerCollectionNew) {
                if (!cpuCorePowerCollectionOld.contains(cpuCorePowerCollectionNewCpuCorePower)) {
                    CpuCore oldIdCoreOfCpuCorePowerCollectionNewCpuCorePower = cpuCorePowerCollectionNewCpuCorePower.getIdCore();
                    cpuCorePowerCollectionNewCpuCorePower.setIdCore(cpuCore);
                    cpuCorePowerCollectionNewCpuCorePower = em.merge(cpuCorePowerCollectionNewCpuCorePower);
                    if (oldIdCoreOfCpuCorePowerCollectionNewCpuCorePower != null && !oldIdCoreOfCpuCorePowerCollectionNewCpuCorePower.equals(cpuCore)) {
                        oldIdCoreOfCpuCorePowerCollectionNewCpuCorePower.getCpuCorePowerCollection().remove(cpuCorePowerCollectionNewCpuCorePower);
                        oldIdCoreOfCpuCorePowerCollectionNewCpuCorePower = em.merge(oldIdCoreOfCpuCorePowerCollectionNewCpuCorePower);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = cpuCore.getId();
                if (findCpuCore(id) == null) {
                    throw new NonexistentEntityException("The cpuCore with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            CpuCore cpuCore;
            try {
                cpuCore = em.getReference(CpuCore.class, id);
                cpuCore.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The cpuCore with id " + id + " no longer exists.", enfe);
            }
            Cpu idCPU = cpuCore.getIdCPU();
            if (idCPU != null) {
                idCPU.getCpuCoreCollection().remove(cpuCore);
                idCPU = em.merge(idCPU);
            }
            Component component = cpuCore.getComponent();
            if (component != null) {
                component.setCpuCore(null);
                component = em.merge(component);
            }
            Collection<CpuCorePower> cpuCorePowerCollection = cpuCore.getCpuCorePowerCollection();
            for (CpuCorePower cpuCorePowerCollectionCpuCorePower : cpuCorePowerCollection) {
                cpuCorePowerCollectionCpuCorePower.setIdCore(null);
                cpuCorePowerCollectionCpuCorePower = em.merge(cpuCorePowerCollectionCpuCorePower);
            }
            em.remove(cpuCore);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<CpuCore> findCpuCoreEntities() {
        return findCpuCoreEntities(true, -1, -1);
    }

    public List<CpuCore> findCpuCoreEntities(int maxResults, int firstResult) {
        return findCpuCoreEntities(false, maxResults, firstResult);
    }

    private List<CpuCore> findCpuCoreEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(CpuCore.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public CpuCore findCpuCore(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(CpuCore.class, id);
        } finally {
            em.close();
        }
    }

    public int getCpuCoreCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<CpuCore> rt = cq.from(CpuCore.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
